package com.example.service_vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.example.commonutils.ResultData;
import com.example.service_vod.service.VodService;
import com.example.service_vod.service.impl.InitVideo;
import com.example.service_vod.utils.ConstantPropertiesUtil;
import com.example.servicebase.exceptionhandler.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/eduvod/video")
public class VodController {
    @Autowired
    private VodService vodService;

    @PostMapping(value = "uploadAliyun",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultData uploadAliyun(MultipartFile file){
        //将视频上传之后，拿到视频的id
        String video=vodService.uploadVideo(file);
        System.out.println(video);
        return ResultData.ok().data("video",video);
    }

    @DeleteMapping(value = "removeVideo/{id}",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultData removeVideo(@PathVariable String id){
        try{
            //初始化对象
            DefaultAcsClient client = InitVideo.initVodClient(ConstantPropertiesUtil.ACCESS_KEY_ID, ConstantPropertiesUtil.ACCESS_KEY_SECRET);
            //创建删除视频的request对象
            DeleteVideoRequest request=new DeleteVideoRequest();
            //设置视频id
            request.setVideoIds(id);
            //调用初始化对象的方法实现删除
            client.getAcsResponse(request);
            //成功则返回
            return ResultData.ok();
        }catch (Exception e){
            throw new CustomException(20001,"删除视频失败");
        }
    }
//  根据视频id获取视频凭证
    @GetMapping("getPlayAuth/{id}")
    public String getPlayAuth(@PathVariable String id){
        try {
            DefaultAcsClient client =
                    InitVideo.initVodClient(ConstantPropertiesUtil.ACCESS_KEY_ID, ConstantPropertiesUtil.ACCESS_KEY_SECRET);
            GetVideoPlayAuthRequest request=new GetVideoPlayAuthRequest();
            request.setVideoId(id);
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            //拿到视频凭证
            String playAuth = response.getPlayAuth();
            return playAuth;
        } catch (ClientException e) {
            throw new CustomException(20001,"播放失败");
        }
    }
}
